var express = require('express');
var router = express.Router();

var Web3 = require("web3");


var web3= new Web3();

web3.setProvider(new Web3.providers.HttpProvider("http://localhost:8545"));

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.get('/regist', function(req, res, next) {
    //res.send('respond with a resource');
    web3.eth.personal.newAccount(req.query["password"], function (error, result) {
        console.log(error);
        console.log(result);
        res.send("ID:"+result);
    });

});
router.get('/getAccounts', function(req, res, next) {
    //res.send('respond with a resource');
      web3.eth.getAccounts(function (error, result) {
          res.send(result);
      });
});
router.get('/unlock', function(req, res, next) {
    //res.send('respond with a resource');
    web3.eth.personal.unlockAccount(req.query["ID"], req.query["password"], function (error, result) {
        console.log(error);
        console.log(result);
        res.send(result);
    });

});

router.get('/balance', function(req, res, next) {
    //res.send('respond with a resource');
    web3.eth.getBalance(req.query["ID"], function (error, result) {
        console.log(error);
        console.log(result);
        res.send(result);
    });
});

router.get('/transfer', function(req, res, next) {
    //res.send('respond with a resource');
    var tx = {
        from: req.query["from"],
        to: req.query["to"],
        value: req.query["value"]
    };
    console.log(req.query["from"]);
    console.log(req.query["to"]);
    console.log(req.query["value"]);
    web3.eth.sendTransaction(tx, function (error, result) {
        console.log(error);
        console.log(result);
        res.send(result);
    });
});

module.exports = router;
